#include "albumwidget.h"

AlbumWidget::AlbumWidget(QWidget *parent)
    : QScrollArea{parent}
{
    w=new QWidget(this);
    listw=new PopupListWidget(this);
    morew=new PopupListWidget(this);
    lastclickitem=nullptr;
    lastplayitem=nullptr;
    lastrightclickitem=nullptr;
    albumtopw=new AlbumTopWidget(w);
    bulkoperationw=new BulkOperationWidget(this);
    songitemfirst=new SongItemFirst(w);
    mainlayout=new QVBoxLayout(w);
    firstlayout=new QHBoxLayout;
    mainlayout->addWidget(albumtopw);
    bulkoperationw->hide();

    //albumtopw->SetAlbumPicture();
    //albumtopw->SetAlbumInfo(9999900,"我喜欢的歌单","这是歌单的简介，因为我不知道个单的简介怎么写，于是就有了这个");
    //albumtopw->SetCreator(QString("E:/SteamLibrary/steamapps/workshop/content/431960/2084174077/preview.jpg"),"创建者",QStringList()<<"acg"<<"华语"<<"日语"<<"流行",QDate(2025,2,13));
    connect(albumtopw,&AlbumTopWidget::playall,this,&AlbumWidget::onPlayAll);
    connect(albumtopw,&AlbumTopWidget::favor,this,&AlbumWidget::onFavor);
    connect(albumtopw,&AlbumTopWidget::download,this,&AlbumWidget::onDownload);
    connect(albumtopw,&AlbumTopWidget::more,this,&AlbumWidget::onMore);
    connect(albumtopw,&AlbumTopWidget::textEdited,this,&AlbumWidget::onTextEdited);

    firstlayout->addWidget(songitemfirst);
    firstlayout->setContentsMargins(20,0,20,0);
    mainlayout->addLayout(firstlayout);

    connect(songitemfirst,&SongItemFirst::selectAll,this,&AlbumWidget::onSelectAll);

    // for(int i=0;i<1;i++)
    // {
    //     auto ptr=new SongItem(w);
    //     ptr->show();
    //     ptr->SetAlbum("专辑");
    //     ptr->SetSongers(QStringList()<<"歌手1"<<"歌手2");
    //     ptr->SetSongName("歌名");
    //     ptr->SetOrder(i+1);
    //     ptr->SetDuration(3,36);
    //     ptr->SetPicture(QString("E:/SteamLibrary/steamapps/workshop/content/431960/830816469/preview.jpg"));
    //     QHBoxLayout*layout=new QHBoxLayout;
    //     layout->addWidget(ptr);
    //     layout->setContentsMargins(20,0,20,0);
    //     mainlayout->addLayout(layout);
    //     hlayouts.push_back(layout);
    //     songitems.push_back(ptr);

    // }

    mainlayout->addStretch(1);

    w->setStyleSheet("QWidget{"
                     "background:#f7f9fc;"
                     "border:none;"
                     "padding: 0px;"
                     "}");
    w->setAttribute(Qt::WA_OpaquePaintEvent);

    for (int i = 0; i < 4; ++i)
    {
        auto item=new QListWidgetItem;
        item->setFont(QFont("Microsoft YaHei",10));
        listw->addItem(item);

    }
    listw->setFixedSize(200,170);
    listw->setStyleSheet("QListWidget::item { "
                         "height: 40px;"
                        "}");
    listw->item(0)->setText("播放");
    listw->item(0)->setIcon(QIcon(":/icon/play.png"));
    listw->item(1)->setText("下一首播放");
    listw->item(1)->setIcon(QIcon(":/icon/nextplay.png"));
    listw->item(2)->setText("收藏");
    listw->item(2)->setIcon(QIcon(":/icon/favorite.png"));
    listw->item(3)->setText("从歌单中删除");
    listw->item(3)->setIcon(QIcon(":/icon/delete.png"));
    connect(listw,&QListWidget::itemClicked,this,&AlbumWidget::onRightListWidgetItemClicked);

    connect(bulkoperationw,&BulkOperationWidget::addPlayList,this,&AlbumWidget::onClickBulkOperationPlayList);
    connect(bulkoperationw,&BulkOperationWidget::download,this,&AlbumWidget::onClickBulkOperationDownload);
    connect(bulkoperationw,&BulkOperationWidget::favor,this,&AlbumWidget::onClickBulkOperationFavor);
    connect(bulkoperationw,&BulkOperationWidget::delete_,this,&AlbumWidget::onClickBulkOperationDelete);
    connect(bulkoperationw,&BulkOperationWidget::OK,this,&AlbumWidget::onClickBulkOperationOK);

    for (int i = 0; i < 3; ++i)
    {
        auto item=new QListWidgetItem;
        item->setFont(QFont("Microsoft YaHei",10));
        morew->addItem(item);
    }
    morew->setFixedSize(200,130);
    morew->setStyleSheet("QListWidget::item { "
                        "height: 40px;"
                        "}");
    morew->item(0)->setText("分享");
    morew->item(0)->setIcon(QIcon(":/icon/.png"));
    morew->item(1)->setText("批量操作");
    morew->item(1)->setIcon(QIcon(":/icon/.png"));
    morew->item(2)->setText("添加全部至播放列表");
    morew->item(2)->setIcon(QIcon(":/icon/.png"));
    connect(morew,&QListWidget::itemClicked,this,&AlbumWidget::onMoreListWidgetItemClicked);

    setWidget(w);
    setWidgetResizable(true);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    setStyleSheet("QScrollArea{"
                  "    border:none;"
                  "}"
                  "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {"
                  "    background: none;"  // 隐藏上下箭头
                  "}");
}

void AlbumWidget::AddSongItem(const QVector<SongItem*>&addsongitems)
{
    for(auto elem:addsongitems){

        connect(elem,&SongItem::chosen,this,&AlbumWidget::onChosen);
        connect(elem,&SongItem::doubleClicked,this,&AlbumWidget::onDoubleClicked);
        connect(elem,&SongItem::mouseRightPress,this,&AlbumWidget::onMouseRightPress);
        connect(elem,&SongItem::updateAlbumPicture,this,[this](const QImage&picture){
            SetAlbumPicture(picture);
        });
        connect(elem,&SongItem::metaDataReady,this,&AlbumWidget::onMetaDataReady);

        elem->setParent(this);
        elem->SetOrder(songitems.size()+1);
        QHBoxLayout*layout=new QHBoxLayout;
        layout->addWidget(elem);
        layout->setContentsMargins(20,0,20,0);
        //mainlayout->addLayout(layout);
        mainlayout->insertLayout(mainlayout->count()-1,layout);
        hlayouts.push_back(layout);
        songitems.push_back(elem);
    }
    albumtopw->SetSmallPrintSongNum(songitems.size());
}

void AlbumWidget::DeleteSongItem(SongItem*delsongitems)
{
    for(qint32 i=0;i<songitems.size();i++)
    {
        if(songitems[i]==delsongitems)
        {
            mainlayout->removeItem(hlayouts[i]);
            mainlayout->removeWidget(songitems[i]);
            hlayouts[i]->deleteLater();
            songitems[i]->deleteLater();
            hlayouts.removeAt(i);
            songitems.removeAt(i);
        }
    }
    for(qint32 i=0;i<songitems.size();i++)
    {
        songitems[i]->SetOrder(i+1);
    }
}

void AlbumWidget::SetSongItemCheck(bool flag)
{
    if(flag)//设置checkmode
    {
        songitemfirst->SetCheckMode(true);
        for (auto&elem:songitems) {
            elem->SetCheckMode(true);
        }
        mainlayout->removeWidget(albumtopw);
        albumtopw->hide();
        mainlayout->insertWidget(0,bulkoperationw);
        bulkoperationw->show();
    }
    else//取消checkmode
    {
        songitemfirst->SetCheckMode(false);
        songitemfirst->SetCheck(false);
        for (auto&elem:songitems) {
            elem->SetCheckMode(false);
            elem->SetCheck(false);
        }
        mainlayout->removeWidget(bulkoperationw);
        bulkoperationw->hide();
        mainlayout->insertWidget(0,albumtopw);
        albumtopw->show();
    }
}

void AlbumWidget::SetMyLike(bool flag)
{
    if(flag)
    {
        for(auto&elem:songitems)
        {
            elem->SetLike();
        }
    }
    else
    {
        for(auto&elem:songitems)
        {
            elem->SetNormal();
        }
    }
}

void AlbumWidget::clean()
{
    for(qint32 i=0;i<hlayouts.size();i++)
    {
        mainlayout->removeItem(hlayouts[i]);
        songitems[i]->hide();
    }
}

void AlbumWidget::onMainWindowResize(const QSize& size)
{
    setGeometry(200,75,size.width()-200,size.height()-75-75);
    w->setFixedWidth(size.width()-200);
}

void AlbumWidget::onMouseRightPress(const QPoint& mousepos)
{
    SongItem* ptr=qobject_cast<SongItem*>(sender());
    //选中样式更改
    ptr->SetChosen();
    if(lastclickitem&&lastclickitem!=ptr)
        lastclickitem->SetNotChosen();
    lastclickitem=ptr;

    listw->move(mousepos);
    listw->show();
    lastrightclickitem=ptr;
}

void AlbumWidget::onHttpsAlubmInfo(const QJsonObject&obj)
{
    QJsonObject data=obj["data"].toObject();
    qint64 albumid=data["album_id"].toInteger();
    QString albumname=data["album_name"].toString();
    qint64 creatorid=data["creator_id"].toInteger();
    QString creatorname=data["creator_name"].toString();
    QDate date=QDate::fromString(data["creator_date"].toString(),"yyyy-MM-dd");
    QString tags=data["tags"].toString();
    QString intro=data["intro"].toString();
    //qint64 playcount=data["play_count"].toInteger();
    //qint64 favorcount=data["favor_count"].toInteger();
    QString filepath=QString("E:/SteamLibrary/steamapps/workshop/content/431960/2084174077/preview.jpg");

    SetAlbumId(albumid);
    SetAlbumInfo(0,albumname,intro);
    SetAlbumCreatorId(creatorid);
    SetAlbumCreatorInfo(filepath,creatorname,QStringList()<<tags,date);

    QJsonArray array=data["songs"].toArray();
    for(int i=0;i<array.size();i++){
        qint64 songid=array[i].toInteger();
        emit getSongInfo(("http://127.0.0.1:8080/songinfo/"+QString::number(songid)));
    }

}

void AlbumWidget::onSongInfoReady(const QJsonObject&obj)
{
    QJsonObject data=obj["data"].toObject();
    auto ptr=SongItem::FromJsonOBJect(data);
    QVector<SongItem*>songitems;
    songitems.push_back(ptr);
    AddSongItem(songitems);

}

void AlbumWidget::onNextSong()
{
    lastplayitem->SetPlayMode(false);
    int i;
    for( i=0;i<songitems.size();i++)
    {
        if(songitems[i]==lastplayitem)
            break;
    }
    lastplayitem=songitems[(i+1)%songitems.size()];
    lastplayitem->SetPlayMode(true);

    emit playSignal(lastplayitem->FilePathUrl());
}

void AlbumWidget::onPreviousSong()
{
    lastplayitem->SetPlayMode(false);
    int i;
    for( i=0;i<songitems.size();i++)
    {
        if(songitems[i]==lastplayitem)
            break;
    }
    lastplayitem=songitems[(i-1+songitems.size())%songitems.size()];
    lastplayitem->SetPlayMode(true);

    emit playSignal(lastplayitem->FilePathUrl());
}

void AlbumWidget::onMetaDataReady()
{
    if(++count==songitems.size())
    {
        ready=true;
        emit flush();
    }
}

void AlbumWidget::onChosen()
{
    SongItem* ptr=qobject_cast<SongItem*>(sender());
    ptr->SetChosen();
    if(lastclickitem&&lastclickitem!=ptr)
        lastclickitem->SetNotChosen();
    lastclickitem=ptr;
}

void AlbumWidget::onDoubleClicked()
{
    qDebug()<<"double click";
    SongItem* ptr=qobject_cast<SongItem*>(sender());
    //选中样式更改
    ptr->SetChosen();
    if(lastclickitem&&lastclickitem!=ptr)
        lastclickitem->SetNotChosen();
    lastclickitem=ptr;

    //播放样式更改
    ptr->SetPlayMode(true);
    if(lastplayitem&&lastplayitem!=ptr)
        lastplayitem->SetPlayMode(false);
    lastplayitem=ptr;

    //播放信号
    emit playSignal(ptr->FilePathUrl());
}

void AlbumWidget::onClickLike()
{
    SongItem* ptr=qobject_cast<SongItem*>(sender());
    emit normalSignal(ptr->id());
}

void AlbumWidget::onClickNormal()
{
    SongItem* ptr=qobject_cast<SongItem*>(sender());
    emit likeSignal(ptr->id());
}

void AlbumWidget::onPlayAll()
{
    if(!songitems.isEmpty())
    {
        emit playSignal(songitems.front()->FilePathUrl());
    }
}

void AlbumWidget::onFavor()
{
    emit favorAlbumSignal(albumid);
}

void AlbumWidget::onDownload()
{
    emit downloadSignal(songitems);
}

void AlbumWidget::onMore(const QPoint&point)
{
    morew->move(point);
    morew->show();
}

void AlbumWidget::onRightListWidgetItemClicked(QListWidgetItem*item)
{
    if(item->text()=="播放")
    {
        emit playSignal(lastrightclickitem->FilePathUrl());

    }
    else if(item->text()=="下一首播放")
    {
        emit addToNextSignal(lastrightclickitem->id());
    }
    else if(item->text()=="收藏")
    {
        emit favorSongSignal(lastclickitem->id());
    }
    else if(item->text()=="从歌单中删除")
    {
        emit deleteSongSignal(albumid,lastclickitem->id());
        DeleteSongItem(lastclickitem);
        lastclickitem=nullptr;
    }
}

void AlbumWidget::onMoreListWidgetItemClicked(QListWidgetItem*item)
{
    if(item->text()=="分享")
    {
        emit shareAlbum(albumid);
    }
    else if(item->text()=="批量操作")
    {
        SetSongItemCheck(true);
    }
    else if(item->text()=="添加全部至播放列表")
    {
        emit  playAllSignal(songitems);
    }
    morew->hide();
}

void AlbumWidget::onClickBulkOperationPlayList()
{
    emit playAllSignal(FindCheckedItem());
    BulkOperationOver();
}

void AlbumWidget::onClickBulkOperationDownload()
{
    emit downloadSignal(FindCheckedItem());
    BulkOperationOver();
}

void AlbumWidget::onClickBulkOperationFavor()
{
    emit favorSignal(FindCheckedItem());
    BulkOperationOver();
}

void AlbumWidget::onClickBulkOperationDelete()
{
    emit deleteSignal(FindCheckedItem());
    BulkOperationOver();
}

void AlbumWidget::onClickBulkOperationOK()
{
    BulkOperationOver();
}

void AlbumWidget::onSelectAll(bool flag)
{
    if(flag)//全选
    {
        for(auto&elem:songitems)
            elem->SetCheck(true);
    }
    else//取消全选
        for(auto&elem:songitems)
            elem->SetCheck(false);
}

void AlbumWidget::onTextEdited(const QString&text)
{
    //首先全部移除，避免之前搜索时带来的影响
    clean();

    if(text.isEmpty())
    {
        for(qint32 i=0;i<hlayouts.size();i++)
        {
            mainlayout->insertLayout(mainlayout->count()-1,hlayouts[i]);
            songitems[i]->show();
        }
    }
    else
    {
        for(qint32 i=0;i<hlayouts.size();i++)
        {
            auto albumname=songitems[i]->AlbumName();
            auto title=songitems[i]->Title();
            auto songers=songitems[i]->Songers();
            if(albumname.contains(text,Qt::CaseInsensitive)||title.contains(text,Qt::CaseInsensitive)
                ||songers.contains(text,Qt::CaseInsensitive))//匹配不区分大小写
            {
                mainlayout->insertLayout(mainlayout->count()-1,hlayouts[i]);
                songitems[i]->show();

            }
        }
    }
}

QVector<SongItem*>AlbumWidget::FindCheckedItem()
{
    QVector<SongItem*>items;
    for(auto&elem:songitems)
    {
        if(elem->isChecked())
        {
            items.push_back(elem);
        }
    }
    return items;
}

void AlbumWidget::BulkOperationOver()
{
    SetSongItemCheck(false);
}
